package com.mky.mkcompany.tool;

import com.alibaba.fastjson.JSONObject;
import com.mky.mkcompany.dic.FileCheckDic;
import com.mky.mkcompany.exception.WafException;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * Created by Lenovo on 2017/9/8.
 */
public class UploadFileUtil {
    private final static Logger LOGGER = Logger.getLogger(UploadFileUtil.class);

    /**
     * 上传文件，主要实现上传到项目同级目录下
     */
    public static JSONObject uploadFile(MultipartFile file,String filePath,int fileTypeCheck){
        JSONObject res=new JSONObject();
        if (!file.isEmpty()) {
            try {
                if(fileTypeCheck== FileCheckDic.IMAGE_FILE_CHECK){ //图片检查
                    FileCheckUtil.uploadImageCheck(file.getInputStream());
                }else if(fileTypeCheck==FileCheckDic.DWG_FILE_CHECK){ //dwg文件检查  CAD

                }
                String projPath = System.getProperty("user.dir");
                String uploadFilePath = file.getOriginalFilename();
                System.out.println("uploadFlePath:" + uploadFilePath);
                // 截取上传文件的文件名
                String fileName = uploadFilePath.substring(
                        uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));
                System.out.println("fileName=" + fileName);
                // 截取上传文件的后缀
                String uploadFileSuffix = uploadFilePath.substring(
                        uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
                System.out.println("uploadFileSuffix:" + uploadFileSuffix);
                String uploadFileName =fileName+"-"+UUID.randomUUID().toString().replace("-","");
                StringBuilder fileUploadPath = new StringBuilder(projPath).append("/").append(filePath).append("/")
                        .append(uploadFileName).append(".").append(uploadFileSuffix);
                System.out.println("fileUploadPath=" + fileUploadPath);
                res.put("fileUploadPath", new StringBuilder(uploadFileName).append(".").append(uploadFileSuffix));
                byte[] bytes = file.getBytes();
                File uploadFile = new File(fileUploadPath.toString());
                //判断目标文件所在的目录是否存在
                if (!uploadFile.getParentFile().exists()) {
                    //如果目标文件所在的目录不存在，则创建父目录
                    if (!uploadFile.getParentFile().mkdirs()) {
                        System.out.println("创建目标文件所在目录失败！");
                    }
                }
                BufferedOutputStream buffStream =
                        new BufferedOutputStream(new FileOutputStream(uploadFile));
                buffStream.write(bytes);
                buffStream.close();
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                throw new WafException("", "上传文件失败，原因：" + e.getMessage(),
                        HttpStatus.NOT_ACCEPTABLE);
            }
        }else{
            throw new WafException("", "不能上传空文件",
                    HttpStatus.NOT_ACCEPTABLE);
        }
        return res;
    }

    /**
     * 上传文件，主要实现上传到项目同级目录下,需要自己创建文件存放目录
     */
    public static JSONObject uploadFile(MultipartFile file, RedirectAttributes redirectAttributes, String filePath){
        JSONObject res = new JSONObject();
        String uploadFilePath =file.getOriginalFilename();
        String uploadFileName= UUID.randomUUID().toString().replace("-","");
        // 截取上传文件的后缀
        String uploadFileSuffix = uploadFilePath.substring(
                uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
        System.out.println("uploadFileSuffix:" + uploadFileSuffix);
        StringBuilder fileUploadPath=new StringBuilder()
                .append(uploadFileName).append(".").append(uploadFileSuffix);
        res.put("fileUploadPath",fileUploadPath);
        if (!file.isEmpty()) {
            try {
                Files.copy(file.getInputStream(), Paths.get(filePath, fileUploadPath.toString()));
                redirectAttributes.addFlashAttribute("message",
                        "You successfully uploaded " + file.getOriginalFilename() + "!");
            } catch (IOException |RuntimeException e) {
                redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
        }
      return res;
    }
}
